﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Inv;
using ESOL.WinUI.UICommon;
using ESOL.Common;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Inv
{
    public partial class frmMaintainCheckingPlan : BaseForm.frmBaseDialogyBusinessForm
    {

        #region Variable
        public InvCheckingPlanEntity SelectedCheckingPlan { get; set; }
        private List<InvCheckingPlanItemEntity> DeleteList = new List<InvCheckingPlanItemEntity>();
        public bool IsCheckingFinished { get; set; }
        #endregion

        #region Construction
        public frmMaintainCheckingPlan()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            List<MstWarehouseEntity> list = MstWarehouseBs.GetMstWarehouseAllList();
            MstWarehouseEntity entity = new MstWarehouseEntity();
            list.Insert(0, entity);
            cmbWareHouse.DataSource = list;
            cmbWareHouse.DisplayMember = "WarehouseName";
            cmbWareHouse.ValueMember = "WarehouseCode";

            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "ICP", false);
        }
        private void BindDataGridDetail()
        {
            if (SelectedCheckingPlan == null)
            {

                gvMain.DataSource = null;
                return;
            }
            //查询
            if (this.ThisActionType == ActionType.View)
            {
                DataSet ds = InvCheckingPlanItemBs.GetDataSetByCheckingId(SelectedCheckingPlan.CheckingPlanId);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    gvMain.DataSource = ds.Tables[0];
                }
                else
                {
                    gvMain.DataSource = null;
                }
            }
            else
            {
                //盘点结束
                if (SelectedCheckingPlan.WarehouseCode != null)
                {

                    DataTable dt = new DataTable();
                    DataTable chkItemTable = InvCheckingPlanItemBs.GetDataSetByCheckingId(SelectedCheckingPlan.CheckingPlanId).Tables[0];
                    if (chkItemTable != null && chkItemTable.Rows.Count > 0)
                    {
                        gvMain.DataSource = chkItemTable;
                    }
                    else
                    {
                        dt = InvStorageBs.GetInvStroageByWareHouseCode(SelectedCheckingPlan.WarehouseCode);

                        dt.Columns.Add("STORAGE_OCCUPIED_QTY", typeof(decimal));
                        dt.Columns.Add("ACTUAL_QTY", typeof(decimal));
                        foreach (DataRow dr in dt.Rows)
                        {
                            dr["LOCATION_CODE"] = MstLocationBs.GetMstLocationByID(dr["LOCATION_ID"].ToString()).LocationCode;
                            dr["STORAGE_OCCUPIED_QTY"] = 0.00;
                            dr["ACTUAL_QTY"] = 0.00;
                        }
                        dt.AcceptChanges();
                        gvMain.DataSource = dt;
                    }
                }
                else
                {
                    DataTable dt = gvMain.DataSource as DataTable;
                    dt.Rows.Clear();
                    gvMain.DataSource = new DataTable();
                }
            }

        }
        private void SetFields()
        {

            BindDataGridDetail();
            if (SelectedCheckingPlan == null)
            {
                return;
            }

            cmbStatus.SetSelectedValue(SelectedCheckingPlan.Status);
            if (ThisActionType != ActionType.New)
            {
                txtCheckingPlanCode.Text = SelectedCheckingPlan.CheckingPlanCode;
            }
            if (SelectedCheckingPlan.PlanDate > DateTime.Now.AddYears(-100))
            {
                dtpCheckingPlanDate.EditValue = SelectedCheckingPlan.PlanDate;
            }
            if (SelectedCheckingPlan.WarehouseCode != null)
            {
                cmbWareHouse.SetSelectedValue(SelectedCheckingPlan.WarehouseCode);
            }
            txtCheckingPerson.Text = SelectedCheckingPlan.CheckingPerson;
            txtCheckingStartDate.Text = SelectedCheckingPlan.BeginDate.ToShortDateString();
            txtRemark.Text = SelectedCheckingPlan.Remark;
            MstPersonEntity CheckingPerson = MstPersonBs.GetMstPersonByID(SelectedCheckingPlan.CheckingPerson);
            if (CheckingPerson != null)
            {
                txtCheckingPerson.Text = CheckingPerson.NameCn;
                txtCheckingPerson.Tag = CheckingPerson;
            }
            else
            {
                txtCheckingPerson.Text = "";
                txtCheckingPerson.Tag = null;
                    
            }
            //UICommonFunctions.SetTextBoxPersonName(txtCheckingPerson, SelectedCheckingPlan.CheckingPerson);
            UICommonFunctions.SetTextBoxDate(txtCheckingStartDate, SelectedCheckingPlan.BeginDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatPerson, SelectedCheckingPlan.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtCheckingEndDate, SelectedCheckingPlan.FinishDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxDate(txtCreatDate, SelectedCheckingPlan.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedPerson, SelectedCheckingPlan.ApprovedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedCheckingPlan.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifyPerson, SelectedCheckingPlan.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifyDate, SelectedCheckingPlan.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
        }
        private void SetEntity()
        {
            if (dtpCheckingPlanDate.EditValue!=null)
            {
                SelectedCheckingPlan.PlanDate = Convert.ToDateTime(dtpCheckingPlanDate.EditValue);
            }
            if (txtCheckingPerson.Tag != null && txtCheckingPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedCheckingPlan.CheckingPerson = ((MstPersonEntity)txtCheckingPerson.Tag).PersonId;
            }
            SelectedCheckingPlan.Remark = txtRemark.Text;
            if (ThisActionType == ActionType.New)
            {
                SelectedCheckingPlan.WarehouseCode = cmbWareHouse.SelectedValue.ToString() ;
                SelectedCheckingPlan.Status = "ICP01";
                SelectedCheckingPlan.CheckingPlanId = Guid.NewGuid().ToString();
                SelectedCheckingPlan.CreatedDate = DateTime.Now;
                SelectedCheckingPlan.CreatedBy = CommonParameter.CurrentUser.PersonId;
                SelectedCheckingPlan.LastModifiedDate = DateTime.Now;
                SelectedCheckingPlan.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.Modify)
            {
                SelectedCheckingPlan.LastModifiedDate = DateTime.Now;
                SelectedCheckingPlan.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.Approve)
            {
                SelectedCheckingPlan.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                SelectedCheckingPlan.ApprovedDate = System.DateTime.Now;
                SelectedCheckingPlan.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                SelectedCheckingPlan.LastModifiedDate = System.DateTime.Now;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtCheckingPerson.Text))
            {
                MessageBox.Show("盘点人员人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpCheckingPlanDate.EditValue == null)
            {
                MessageBox.Show("计划盘点日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            //if (gvMain.DataSource == null || gvMain.Rows.Count == 0)
            //{
            //    MessageBox.Show("申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return false;
            //}
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    //bool isSuccessful = InvCheckingPlanBs.SaveCheckingPlan(true, SelectedCheckingPlan, dt, DeleteList);
                    bool isSuccessful = InvCheckingPlanBs.SaveCheckingPlan(true, SelectedCheckingPlan);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = InvCheckingPlanBs.ModifyCheckingPlan(false,SelectedCheckingPlan, dt);//InvCheckingPlanBs.SaveCheckingPlan(true, SelectedCheckingPlan, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = InvCheckingPlanBs.UpdateInvCheckingPlan(SelectedCheckingPlan);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    InvCheckingPlanBs.ModifyCheckingPlan(true, SelectedCheckingPlan, dt);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        private void ResetButtonEnable()
        {
            btnCheckingOK.Enabled = false;
            if (IsCheckingFinished)
            {
                btnCheckingOK.Enabled = true;
                btnApprove.Enabled = false;
                btnReject.Enabled = false;
                btnSave.Enabled = true;
                btnSaveNew.Enabled = false;
                dtpCheckingPlanDate.Enabled = false;
            }
            //cmbWareHouse.Enabled = false;
        }
        #endregion


        #region Events
        private void frmMaintainCheckingPlan_Load(object sender, EventArgs e)
        {
            cmbWareHouse.Enabled = false;
            if (ThisActionType == ActionType.New)
            {
                
                SelectedCheckingPlan = new InvCheckingPlanEntity();
            }
            if (this.ThisActionType == ActionType.New || this.ThisActionType == ActionType.Modify || this.ThisActionType == ActionType.Approve)
            {
                cmbWareHouse.Enabled = true;
                gvMain.Enabled = false;
                gridView1.Columns["STORAGE_OCCUPIED_QTY"].Visible = false;
                gridView1.Columns["ACTUAL_QTY"].Visible = false;

            }
            
            ResetButtonEnable();
            BindComboBox();
            SetFields();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedCheckingPlan = new InvCheckingPlanEntity();
                SetFields();
            }
        }
        protected override void Click_Approve()
        {
            if (SelectedCheckingPlan == null)
            {
                return;
            }
            SelectedCheckingPlan.Status = "ICP02";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedCheckingPlan == null)
            {
                return;
            }
            SelectedCheckingPlan.Status = "ICP03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtCheckingPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtCheckingPerson.Text = frm.SelectedPerson.NameCn;
                txtCheckingPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtCheckingPerson.Text = "";
                txtCheckingPerson.Tag = null;
            }
        }

        private void cmbWareHouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                if (cmbWareHouse.SelectedValue != null)
                {
                    DataTable dt = new DataTable();
                    dt = InvStorageBs.GetInvStroageByWareHouseCode(cmbWareHouse.SelectedValue.ToString());

                    dt.Columns.Add("STORAGE_OCCUPIED_QTY", typeof(decimal));
                    //dt.Columns.Add("ACTUAL_QTY", typeof(decimal));
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["LOCATION_CODE"] = MstLocationBs.GetMstLocationByID(dr["LOCATION_ID"].ToString()).LocationCode;
                        dr["STORAGE_OCCUPIED_QTY"] = 0.00;
                    }
                    dt.AcceptChanges();
                    gvMain.DataSource = dt;
                }
                else
                {
                    DataTable dt = gvMain.DataSource as DataTable;
                    dt.Rows.Clear();
                    //gvMain.DataSource = new DataTable();
                }
            }
        }

        private void btnCheckingOK_Click(object sender, EventArgs e)
        {
            DataTable dt = gvMain.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i]["STORAGE_OCCUPIED_QTY"].ToString()))
                {
                    MessageBox.Show("第" + (i + 1).ToString() + "行盘点数量为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            SetEntity();
            //bool isSuccessful = InvCheckingPlanBs.FinishCheckingPlan(SelectedCheckingPlan, dt, DeleteList);
            bool isSuccessful = InvCheckingPlanBs.FinishCheckingPlan(SelectedCheckingPlan, dt);
            if (!isSuccessful)
            {
                MessageBox.Show("提交失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private DataRow selectedRow;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            selectedRow = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void ItemAdd_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt=gvMain.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dr["CURRENT_STORAGE_QTY"] = Convert.ToDecimal(0);
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }

        private void ItemDelete_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (selectedRow == null)
            {
                return;
            }
            //if (selectedRow.RowState == DataRowState.Added)
            //{
                //InvCheckingPlanItemEntity entity = new InvCheckingPlanItemEntity(selectedRow);
                //DeleteList.Add(entity);
            //}
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(selectedRow);
            dt.AcceptChanges();
        }

        private void repPRODUCT_CODE_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            DialogResult dr = frm.ShowDialog();
            DataTable dt=gridView1.DataSource as DataTable;
            
            if (dr == DialogResult.OK && frm.SelectedProduct != null)
            {
                if (selectedRow != null)
                {
                    DataTable inv_dt = InvStorageBs.GetInvStroageByWareHouseCode(SelectedCheckingPlan.WarehouseCode);

                    foreach (DataRow rw in inv_dt.Rows)
                    {

                        if (rw["PRODUCT_CODE"].ToString() == frm.SelectedProduct.ProductCode)
                        {
                            MessageBox.Show("该物料已存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    selectedRow["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                    selectedRow["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                    selectedRow["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                    MstProductTypeEntity typeEntity_2 = MstProductTypeBs.GetMstProductTypeByID(frm.SelectedProduct.ProductTypeId);
                    selectedRow["CLASS2"] = typeEntity_2.ProductTypeName;
                    MstProductTypeEntity typeEntity_1 = MstProductTypeBs.GetMstProductTypeByID(typeEntity_2.ParentTypeId);
                    selectedRow["CLASS1"] = typeEntity_1.ProductTypeName;

                    selectedRow["CURRENT_STORAGE_QTY"] = InvStorageBs.GetActualStorageQty(frm.SelectedProduct.ProductId, SelectedCheckingPlan.WarehouseCode);
                }
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

            if(selectedRow ==null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(selectedRow["STORAGE_OCCUPIED_QTY"].ToString()) && !string.IsNullOrEmpty(selectedRow["CURRENT_STORAGE_QTY"].ToString()))
            {
                selectedRow["ACTUAL_QTY"] = Convert.ToDecimal(selectedRow["STORAGE_OCCUPIED_QTY"].ToString()) - Convert.ToDecimal(selectedRow["CURRENT_STORAGE_QTY"].ToString());

            }
        }
        #endregion

    }
}